/**
 * 压缩指定项目的静态资源
 * 安装: npm install csso uglify-js
 * @link https://github.com/css/csso
 * @link https://www.npmjs.com/package/uglify-js
 * @version 1.0.1
 */
const csso = require('csso');
const UglifyJS = require("uglify-js");
const fs = require('fs');

// 配置项目静态资源文件路径
const adminDir = '../../public/admin/static/eladmin/';
const projects = {
    veladmin: {
        css: [
            {
                from: [
                    '../../public/admin/static/eladmin/css/login.css',
                    '../../public/admin/static/eladmin/css/index.css',
                    '../../public/admin/static/eladmin/css/utility.css',
                    '../../public/admin/static/eladmin/css/eladmin.css',
                ],
                to: '../../public/admin/static/eladmin/css/eladmin.min.css',
            },
        ],
        js: [
            {
                from: [
                    '../../public/admin/static/js/EsConfig.js',
                    '../../public/admin/static/js/EsUtils.js',
                    '../../public/admin/static/js/LoginState.js',
                ],
                to: '../../public/admin/static/js/utils.min.js',
            },
            {
                from: [
                    '../../public/admin/static/eladmin/js/elcomponents.js',
                    '../../public/admin/static/eladmin/js/eladmin.js',
                ],
                to: '../../public/admin/static/eladmin/js/elcomponents.min.js',
            },
            {
                from: ['../../public/admin/static/mock/admin/api-route.js'],
                to: '../../public/admin/static/mock/admin/api-route.min.js'
            }
        ]
    }
}

// 执行合并压缩指定项目的静态资源
let project = projects.veladmin;
minifyCss(project.css);
minifyJs(project.js);

/**
 * 合并 CSS 文件并压缩
 * @param {Array} data 
 */
function minifyCss(data) {
    let text = '';
    data.forEach(item => {
        text = '';
        item.from.forEach(file => {
            if (!fs.existsSync(file)) {
                console.log('[css] 文件不存在: ', file);
                return;
            }
            text += fs.readFileSync(file, 'utf8');
            console.log('[css] 处理文件: ', file);
        })
        if (text.length == 0) {
            console.log('[css] 没有需要处理的文件！');
            return;
        }
        fs.writeFileSync(item.to, csso.minify(text).css)
        console.log('[css] 压缩成功:', item.to);
    })
}

/**
 * 合并 JS 文件并压缩
 * @param {Array} data 
 */
function minifyJs(data) {
    let text = '';
    data.forEach(item => {
        text = '';
        item.from.forEach(file => {
            if (!fs.existsSync(file)) {
                console.log('[js] 文件不存在: ', file);
                return;
            }
            text += fs.readFileSync(file, 'utf8');
        })
        if (text.length == 0) {
            console.log('[js] 没有需要处理的文件！');
            return;
        }
        fs.writeFileSync(item.to, UglifyJS.minify(text).code)
        console.log('[js] 压缩成功:', item.to);
    })
}